<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form';
import { addressSchema } from './data';

export default defineComponent({
  components: { BasicModal, BasicForm },
  emits: ['addressData'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
      labelWidth: 100,
      schemas: addressSchema,
      showActionButtonGroup: false,
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      let formData = data.record;

      if (unref(isUpdate)) {
        setFieldsValue({
          ...formData,
        });
      }
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增地址' : '修改地址'));

    async function handleSubmit() {
      const values = await validate();
      closeModal();
      emit('addressData', values); //返回数据给父页面
    }

    return { registerModal, registerForm, getTitle, handleSubmit };
  },
});
</script>
